package com.lzp.java.concurrent.jmm;

import java.util.concurrent.atomic.AtomicInteger;

/**
 * @author lzp
 * @date 2020/02/24
 */
public class UseVolatile implements Runnable {
    private volatile boolean flag;
    private AtomicInteger realIndex = new AtomicInteger();

    @Override
    public void run() {
        for (int i = 0; i < 10000; i++) {
            doSomething();
            realIndex.incrementAndGet();
        }
    }

    private void doSomething() {
        // flag = true;
        flag = !flag;
    }

    public static void main(String[] args) throws InterruptedException {
        Runnable task = new UseVolatile();
        Thread thread1 = new Thread(task);
        Thread thread2 = new Thread(task);
        thread1.start();
        thread2.start();
        thread1.join();
        thread2.join();
        System.out.println("运行结果：" + ((UseVolatile) task).flag);
        System.out.println("实际运行次数：" + ((UseVolatile) task).realIndex);
    }

}
